package com.chiang.myscrollview.ui;

import android.content.Context;
import android.os.SystemClock;

/**
 * @author Chiang.CMBA
 * @date Created on: 2015-3-1 上午10:43:45
 * @version v1.0
 * @Description: MyScroller is supposed to make the scrolling animation look smooth.
 */

public class MyScroller {
	
	private static final int DEFAULT_DURATION = 300;
	
	private Context mContext;

	private boolean mIsFinished;

	private int mStartX;

	private int mStartY;

	private int mCurrX;
	
	private int mCurrY;
	
	private int mDx;

	private int mDy;
	
	private int mDuration;

	private long mStartTime;

	private int mFinalX;

	private int mFinalY;
	
	public MyScroller(Context context){
		mContext = context;
	}
	
	
	 public int getCurrX() {
		return mCurrX;
	}


	public void setCurrX(int mCurrX) {
		this.mCurrX = mCurrX;
	}


	public int getCurrY() {
		return mCurrY;
	}


	public void setCurrY(int mCurrY) {
		this.mCurrY = mCurrY;
	}


	/**
     * Call this when you want to know the new location.  If it returns true,
     * the animation is not yet finished.
     */
	public boolean computeScrollOffset(){
		if(mIsFinished){
			return false;
		}
		long diffTime = SystemClock.uptimeMillis() - mStartTime;
		// 如果时间还在允许的范围内
		if(diffTime < mDuration){
			// 当前的位置  =  开始的位置  +  移动的距离（距离 = 速度*时间）
			mCurrX = (int) (mStartX + (mDx * diffTime)/mDuration);
			mCurrY = (int) (mStartY + (mDy * diffTime)/mDuration);
			mIsFinished = false;
		}else{
			mCurrX = mFinalX;
			mCurrY = mFinalY;
			mIsFinished = true;
		}
		return true;
	}
	
	/**
     * Start scrolling by providing a starting point and the distance to travel.
     * The scroll will use the default value of 300 milliseconds for the
     * duration.
     * 
     * @param startX Starting horizontal scroll offset in pixels. Positive
     *        numbers will scroll the content to the left.
     * @param startY Starting vertical scroll offset in pixels. Positive numbers
     *        will scroll the content up.
     * @param dx Horizontal distance to travel. Positive numbers will scroll the
     *        content to the left.
     * @param dy Vertical distance to travel. Positive numbers will scroll the
     *        content up.
     */
    public void startScroll(int startX, int startY, int dx, int dy) {
    	mIsFinished = false;
    	mStartX = startX;
    	mStartY = startY;
    	mDx = dx;
    	mDy = dy;
    	mFinalX = mStartX + mDx;
    	mFinalY = mStartX + mDx;
    	mDuration = DEFAULT_DURATION;
    	mStartTime = SystemClock.uptimeMillis();
    }
}
